﻿using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using PoemGame.Domain.PlayerAggregate;

namespace PoemGame.Repository.EF
{
    public class PlayerRepository:IPlayerRepository
    {
        private readonly PoemGameDbContext dbContext;
        public PlayerRepository(PoemGameDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        public async Task<Player?> GetPlayerByUserNameAsync(string username)
        {
            var player = await dbContext.Players.FirstOrDefaultAsync(o=>o.UserName==username);
            return player;
        }

        public async Task<Player?> GetPlayerByIdAsync(Guid id)
        {
            var player= await dbContext.Players.FindAsync(id);
            return player;
        }

        public async Task<Guid> AddAsync(Player player)
        {
            await dbContext.Players.AddAsync(player);

            await dbContext.SaveChangesAsync();

            return player.Id;
        }

        public async Task RemoveAsync(Player player)
        {
            dbContext.Players.Remove(player);
            await dbContext.SaveChangesAsync();
        }

        public async Task UpdateAsync(Player player)
        {
            dbContext.Players.Update(player);
            await dbContext.SaveChangesAsync();
        }

        public async Task<IEnumerable<Player>> GetAllAsync()
        {
            return await dbContext.Players.ToListAsync();
        }

        public async Task<IEnumerable<Player>> GetByConditionAsync(Expression<Func<Player, bool>> predicate)
        {
            return await dbContext.Players.Where(predicate).ToListAsync();
        }
    }
}
